package com.xzj.common.file.excel.handle;

import com.alibaba.excel.metadata.Head;
import com.alibaba.excel.metadata.data.WriteCellData;
import com.alibaba.excel.write.handler.CellWriteHandler;
import com.alibaba.excel.write.handler.context.CellWriteHandlerContext;
import com.alibaba.excel.write.metadata.holder.WriteSheetHolder;
import com.alibaba.excel.write.metadata.holder.WriteTableHolder;
import com.xzj.common.file.excel.function.ColumnHandleFunction;
import com.xzj.common.file.excel.style.CustomCellStyle;
import org.apache.poi.ss.usermodel.*;

import java.util.List;

/**
 * @program: xzj-test
 * @ClassName: CustomWriteHandler
 * @description: 自定义导出单元格写入样式
 * @author: XiaZunJun
 * @create: 2024-08-21 15:16
 */
public class CustomWriteHandler implements CellWriteHandler {

    /**
     * 自定义各列的样式处理函数
     */
    private ColumnHandleFunction columnHandleFunction;

    /**
     * 创建带函数的处理器
     * @author XiaZunJun
     * @date 2024/8/26 上午9:29
     * @param columnHandleFunction 自定义各列的样式函数
     *
     */
    public CustomWriteHandler(ColumnHandleFunction columnHandleFunction) {
        this.columnHandleFunction = columnHandleFunction;
    }

    /**
     * 创建不带函数的处理器
     * @author XiaZunJun
     * @date 2024/8/26 上午9:29
     */
    public CustomWriteHandler() {
    }

    @Override
    public void afterCellDispose(CellWriteHandlerContext context) {
        context.getFirstCellData().setWriteCellStyle(null);
        CellWriteHandler.super.afterCellDispose(context);
    }

    @Override
    public void afterCellDispose(WriteSheetHolder writeSheetHolder, WriteTableHolder writeTableHolder, List<WriteCellData<?>> cellDataList, Cell cell, Head head, Integer relativeRowIndex, Boolean isHead) {
        writeSheetHolder.getSheet().setColumnWidth(cell.getColumnIndex(), 16*256);
        Workbook workbook = writeSheetHolder.getSheet().getWorkbook();
        CellStyle cellStyle;
        if(isHead){
            cellStyle = CustomCellStyle.createHeaderCellStyle(workbook);
        }else {
            cellStyle = CustomCellStyle.createContentCellStyle(workbook);
            if(null != this.columnHandleFunction){
                String fieldName;
                if(null != head){
                    fieldName = head.getFieldName();
                }else{
                    // 自定义导出的方法
                    List<String> fieldList = (List<String>) writeSheetHolder.getIncludeColumnFieldNames();
                    int index = cell.getColumnIndex();
                    fieldName = fieldList.get(index);
                }
                this.columnHandleFunction.apply(cell, workbook, cellStyle, fieldName);
            }
        }
        cell.setCellStyle(cellStyle);
    }


}
